﻿Imports Microsoft.Win32
Imports System.Windows

Namespace TweeVo
	''' <summary>
	''' Interaction logic for TweeVoWindow.xaml
	''' </summary>
	Partial Public Class TweeVoWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
			MyBase.AddHandler(Hyperlink.RequestNavigateEvent, New RoutedEventHandler(AddressOf App.OnRequestNavigation))
		End Sub

		Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
			AddHandler TiVoBeaconListener.TiVoFound, AddressOf TiVoBeaconListener_TiVoFound
			TiVoBeaconListener.Start()

			Dim prefixItems As New List(Of PrefixItem)()
			prefixItems.Add(New PrefixItem(PrefixType.Nothing, "Nothing"))
			prefixItems.Add(New PrefixItem(PrefixType.TiVo, "TiVo>"))
			prefixItems.Add(New PrefixItem(PrefixType.Name, "(TiVo Name)>"))
			cboPrefix.ItemsSource = prefixItems
			cboPrefix.DisplayMemberPath = "PrefixDescription"
			cboPrefix.SelectedValuePath = "PrefixType"

			Dim suggestionItems As New List(Of SuggestionItem)()
			suggestionItems.Add(New SuggestionItem(SuggestionsType.NoShow, "Don't show"))
			suggestionItems.Add(New SuggestionItem(SuggestionsType.ShowNormal, "Tweet like a regular show"))
			suggestionItems.Add(New SuggestionItem(SuggestionsType.ShowWithPrefix, "Tweet with (S) prefix"))
			cboSuggestions.ItemsSource = suggestionItems
			cboSuggestions.DisplayMemberPath = "SuggestionDescription"
			cboSuggestions.SelectedValuePath = "SuggestionType"

			If TweeVoSettings.Default.TiVos IsNot Nothing Then
				lbTiVo.Items.Clear()

				For Each tivo As TiVo In TweeVoSettings.Default.TiVos.Values
					Dim t As TiVo = tivo
					Dispatcher.BeginInvoke(New Action(Function() lbTiVo.Items.Add(t)))
				Next tivo

				grid.DataContext = TweeVoSettings.Default
				txtTwitterPassword.Password = TweeVoSettings.Default.TwitterPassword.DecryptString()
			End If

			txtVersion.Text = "v" & System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
		End Sub

		Private Sub TiVoBeaconListener_TiVoFound(ByVal sender As Object, ByVal e As TiVoFoundEventArgs)
			Dispatcher.BeginInvoke(New Action(Function() lbTiVo.Items.Add(e.TiVo)))
		End Sub

		Private Sub btnSave_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			If Not VerifySettings() Then
				Return
			End If

			StartWithWindows(TweeVoSettings.Default.StartWithWindows)

			TweeVoSettings.Default.TwitterPassword = txtTwitterPassword.Password.EncryptString()
			TweeVoSettings.Default.Save()

			MessageBox.Show("Settings saved.", "TweeVo", MessageBoxButton.OK, MessageBoxImage.Information)

			Me.Hide()

			TiVoPoller.Start()
		End Sub

		Private Function SetError(ByVal control As IInputElement, ByVal msg As String) As Boolean
			MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error)
			control.Focus()
			Return False
		End Function

		Private Function VerifySettings() As Boolean
			If String.IsNullOrEmpty(txtTwitterUsername.Text) Then
				Return SetError(txtTwitterUsername, "Please enter your Twitter username.")
			End If

			If String.IsNullOrEmpty(txtTwitterPassword.Password) Then
				Return SetError(txtTwitterPassword, "Please enter your Twitter password.")
			End If

			If TweeVoSettings.Default.TiVos Is Nothing OrElse TweeVoSettings.Default.TiVos.Count = 0 Then
				Return SetError(lbTiVo, "Please wait for the TiVo list to populate.")
			End If

			If TweeVoSettings.Default.TiVos.Count = 0 Then
				Return SetError(lbTiVo, "Please select at least one TiVo.")
			End If

			If String.IsNullOrEmpty(txtMAK.Text) OrElse txtMAK.Text.Length <> 10 Then
				Return SetError(lbTiVo, "Please enter your 10 digit Media Access Key.")
			End If

			If Not Twitter.VerifyTwitterCredentials(txtTwitterUsername.Text, txtTwitterPassword.Password) Then
				Return SetError(txtTwitterUsername, "Your Twitter credentials are invalid.")
			End If

			If Not( _
			    From t In TweeVoSettings.Default.TiVos.Values _
			    Where t.Active _
			    Select t).First().VerifyMAK(txtMAK.Text) Then
				Return SetError(lbTiVo, "Your Media Access Key is invalid.")
			End If

			Return True
		End Function

		Private Sub Window_StateChanged(ByVal sender As Object, ByVal e As EventArgs)
			If WindowState = WindowState.Minimized Then
				Me.Hide()
			End If
		End Sub

		Private Sub btnExit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			Me.Close()
		End Sub

		Private Sub StartWithWindows(ByVal start As Boolean)
			Using hkcu As RegistryKey = Registry.CurrentUser
				Using runKey As RegistryKey = hkcu.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
					If runKey Is Nothing Then
						Return
					End If

					If start Then
						runKey.SetValue("TweeVo", System.Reflection.Assembly.GetEntryAssembly().Location)
					Else
						If runKey.GetValue("TweeVo") IsNot Nothing Then
							runKey.DeleteValue("TweeVo")
						End If
					End If
				End Using
			End Using
		End Sub

		Private Sub Window_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
			If MessageBox.Show("Are you sure you want to exit TweeVo?", "TweeVo", MessageBoxButton.YesNo, MessageBoxImage.Question) = MessageBoxResult.Yes Then
				e.Cancel = False
			Else
				e.Cancel = True
			End If
		End Sub
	End Class

	<Serializable> _
	Public Class PrefixItem
		Private privatePrefixType As PrefixType
		Public Property PrefixType() As PrefixType
			Get
				Return privatePrefixType
			End Get
			Set(ByVal value As PrefixType)
				privatePrefixType = value
			End Set
		End Property
		Private privatePrefixDescription As String
		Public Property PrefixDescription() As String
			Get
				Return privatePrefixDescription
			End Get
			Set(ByVal value As String)
				privatePrefixDescription = value
			End Set
		End Property

		Public Sub New(ByVal type As PrefixType, ByVal description As String)
			PrefixType = type
			PrefixDescription = description
		End Sub
	End Class

	<Serializable> _
	Public Class SuggestionItem
		Private privateSuggestionType As SuggestionsType
		Public Property SuggestionType() As SuggestionsType
			Get
				Return privateSuggestionType
			End Get
			Set(ByVal value As SuggestionsType)
				privateSuggestionType = value
			End Set
		End Property
		Private privateSuggestionDescription As String
		Public Property SuggestionDescription() As String
			Get
				Return privateSuggestionDescription
			End Get
			Set(ByVal value As String)
				privateSuggestionDescription = value
			End Set
		End Property

		Public Sub New(ByVal type As SuggestionsType, ByVal description As String)
			SuggestionType = type
			SuggestionDescription = description
		End Sub
	End Class
End Namespace
